package com.wkkun.particle.base

import android.content.Context
import android.graphics.Canvas
import android.os.Handler
import android.util.AttributeSet
import android.view.View
import com.wkkun.particle.util.Constant
import com.wkkun.particle.util.ScreenUtil
import java.util.*
import kotlin.collections.ArrayList

/**
 *Date:2020/5/8
 *Author:wang kunkun
 *Des:
 **/
class ParticleView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet),
    BaseParticle, Runnable {
    private var particleAdapter: ParticleAdapter? = null
    private var isAutoPlay = true
    private var intervalTime = 10 * Constant.RENDER_TIME
    private var renderTime = Constant.RENDER_TIME
    private var increaseParticleCount = 1
    private var childTotal = Int.MAX_VALUE
    private var temTime = -1


    //缓存的view
    private var cacheItems = LinkedList<BaseItem>()
    //要绘制的所有View
    private var drawItems = ArrayList<BaseItem>()

    private var renderHandler: Handler = Handler()

    private var isInit: Boolean = false

    override fun preCreate() {
        repeat(particleAdapter?.preCreateCount() ?: 0) {
            val newItem = particleAdapter!!.newItem(measuredWidth, measuredHeight)
            newItem.preInit(context)
            drawItems.add(newItem)
        }
    }

    override fun getItem(): BaseItem {
        val newItem = if (cacheItems.size > 0) {
            cacheItems.removeFirst()
        } else {
            particleAdapter!!.newItem(measuredWidth, measuredHeight)
        }
        newItem.init(context)
        return newItem
    }

    override fun drawItems(canvas: Canvas) {
        if (drawItems.size < childTotal) {
            if (temTime == -1) {
                temTime = ((intervalTime / renderTime.toFloat() + 0.5).toInt())
            } else if (temTime == 0) {
                repeat(increaseParticleCount) {
                    drawItems.add(getItem())
                }
            }
            temTime--
        }
        drawItems.forEach {
            it.draw(canvas)
        }
    }

    override fun transForms() {
        val iterator = drawItems.iterator()
        while (iterator.hasNext()) {
            val next = iterator.next()
            val isLive = next.move()
            if (!isLive) {
                iterator.remove()
                cacheItems.add(next)
            }
        }
    }

    override fun destroyAllView() {
        drawItems.forEach {
            it.destroy()
        }
        cacheItems.forEach {
            it.destroy()
        }
    }

    override fun startAnimation() {
        renderHandler.removeCallbacks(this)
        renderHandler.post(this)
    }

    override fun stopAnimation() {
        renderHandler.removeCallbacks(this)
    }

    override fun setAdapter(adapter: ParticleAdapter) {
        particleAdapter = adapter
        if (particleAdapter!!.maxParticleCount() <= 0) {
            return
        }
        childTotal = particleAdapter!!.maxParticleCount()
    }

    override fun setRenderTime(renderTime: Long) {
        if (intervalTime < renderTime || renderTime < 0) {
            return
        }
        this.renderTime = renderTime
    }

    override fun setIncreaseParticleInterval(intervalTime: Long) {
        if (intervalTime < renderTime || renderTime < 0) {
            return
        }
        this.intervalTime = intervalTime
    }

    override fun setIncreaseParticleCount(count: Int) {
        if (count <= 0) {
            return
        }
        increaseParticleCount = count
    }

    override fun setIsAutoPlay(isAuto: Boolean) {
        isAutoPlay = isAuto
    }

    /**
     * 设置大小则按照设置的大小计算 否则按照屏幕的宽高来计算
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        //获取屏幕宽高
        val screenWidth = ScreenUtil.getScreenWidth(context)
        val screenHeight = ScreenUtil.getScreenRealHeight(context)
        setMeasuredDimension(
            getDefaultSize(screenWidth, widthMeasureSpec),
            getDefaultSize(screenHeight, screenHeight)
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        if (!isInit) {
            isInit = true
            preCreate()
        }
    }

    override fun onDraw(canvas: Canvas?) {
        if (visibility != VISIBLE) {
            return
        }
        if (canvas == null) {
            renderHandler.removeCallbacks(this)
            return
        }
        drawItems(canvas)
    }

    override fun run() {
        transForms()
        invalidate()
        renderHandler.postDelayed(this, renderTime)
    }

    override fun setVisibility(visibility: Int) {
        super.setVisibility(visibility)
        if (isAutoPlay) {
            if (visibility == VISIBLE) {
                startAnimation()
            } else {
                renderHandler.removeCallbacksAndMessages(null)
            }
        }
    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        renderHandler.removeCallbacks(this)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        renderHandler.post(this)
    }


}